<template>
	<view>
		<custom-tree-select 
			v-model="selectedArr"
			:dataLabel="defaultProps.label"
			:dataValue="defaultProps.value"
			:dataChildren="defaultProps.children"
			:mutiple="checkbox"
			:linkage="linkage"
			:disabled="disabled || !writable"
			:listData="listData" 
			:clearable="clearable"
			:search="search"
			:choseParent="choseParent"
			:placeholder="placeholder"
			@change="treeSelectChange"
			@input="treeSelectInput"
		/>
		<view v-show="required && validator" class="requiredMessage">{{ requiredMessage }}</view>
	</view>
</template>

<script>
import customTreeSelect from '../custom-tree-select/custom-tree-select.vue'
export default {
	data() {
		return {
			selectedArr: [],
			validator: false,
			linkage: false,
			choseParent: false
		};
	},
	components: { customTreeSelect },
	props: {
		value: {
			type: [Array, String],
			default: () => []
		},
		placeholder: {
			type: String,
			default: '请选择内容'
		},
		required: {
			type: Boolean,
			default: false
		},
		requiredMessage: {
			type: String,
			default: '值不能为空'
		},
		disabled: {
			type: Boolean,
			default: false
		},
		writable: {
			type: Boolean,
			default: true
		},
		defaultProps: {
			type: Object,
			default: () => ({ label: 'label', value: 'value', children: 'children' })
		},
		checkbox: {
			type: Boolean,
			default: false
		},
		isOnlySelectLeaf: {
			type: Boolean,
			default: false
		},
		clearable: {
			type: Boolean,
			default: false
		},
		search: {
			type: Boolean,
			default: false
		},
		listData: {
			type: Array,
			default: () => ([])
		}
	},
	computed: {
		validateStatus() {
			return this.$store?.state?.validate?.status || false
		}
	},
	watch: {
		value: {
			handler () {
				this.selectedArr = this.value
			},
			immediate: true,
			deep: true
		},
		validateStatus() {
			if(this.validateStatus && this.required) {
				if(this.selectedArr == '' || !this.selectedArr.length) {
					this.validator = true
				} else {
					this.validator = false
				}
			}
		},
		selectedArr() {
			if(this.validateStatus && this.required) {
				if(this.selectedArr == '' || !this.selectedArr.length) {
					this.validator = true
				} else {
					this.validator = false
				}
			}
		},
		checkbox: {
			handler() {
				if(this.checkbox) {
					this.linkage = true
					this.choseParent = true
				} else {
					this.linkage = false
					if(this.isOnlySelectLeaf) {
						this.choseParent = false
					} else {
						this.choseParent = true
					}
				}
			},
			immediate: true
		}
	},
	methods: {
		treeSelectChange(data) {
			console.log(data, 'treeSelectChange')
		},
		treeSelectInput(data) {
			this.$emit('input', this.selectedArr)
		}
	}
}
</script>

<style scoped>
.requiredMessage {
	width: 100%;
	height: 50rpx;
	line-height: 50rpx;
	color: #f56c6c;
	font-size: 22rpx;
}
</style>